/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DataLayer.KnowledgeBase;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.imageio.ImageIO;

/**
 * Stores an image in bytes, can be serialized.
 * @author Kovács Áron
 */
public class SerializableBufferedImage implements Serializable {

    public static final long serialVersionUID = 2403614245235048575L;
    private byte[] byteImage = null;
    private String sID;

    /**
     * The constructor.
     */
    public SerializableBufferedImage() {
        sID = "null";
    }

    /**
     * Constructor with an image parameter, transforms it into a byte array.
     * @param bufferedImage
     * @throws NoSuchAlgorithmException
     */
    public SerializableBufferedImage(BufferedImage bufferedImage) throws NoSuchAlgorithmException {
        this.byteImage = toByteArray(bufferedImage);

        MessageDigest m = MessageDigest.getInstance("MD5");
        m.update(byteImage, 0, byteImage.length);
        sID = new BigInteger(1, m.digest()).toString(16);
    }

    /**
     * Retiurns the image ID.
     * @return - The image ID.
     */
    public String getID() {
        return sID;
    }

    /**
     * Returns the image (from the byte array).
     * @return - The image.
     */
    public BufferedImage getBufferedImage() {
        return fromByteArray(byteImage);
    }

    /**
     * Transforms the byte array data into an image.
     * @param imagebytes - The byte array.
     * @return - The image.
     */
    private BufferedImage fromByteArray(byte[] imagebytes) {
        try {
            if (imagebytes != null && (imagebytes.length > 0)) {
                BufferedImage im = ImageIO.read(new ByteArrayInputStream(imagebytes));
                return im;
            }
            return null;
        } catch (IOException e) {
            throw new IllegalArgumentException(e.toString());
        }
    }

    /**
     * Transforms an image into a byte array.
     * @param bufferedImage - The image.
     * @return - The byte array.
     */
    private byte[] toByteArray(BufferedImage bufferedImage) {
        if (bufferedImage != null) {
            BufferedImage image = bufferedImage;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                ImageIO.write(image, "png", baos);
            } catch (IOException e) {
                throw new IllegalStateException(e.toString());
            }
            byte[] b = baos.toByteArray();
            return b;
        }
        return new byte[0];
    }
}
